#include "head.h"

/*
Usage:
 */
int work_program(int client_fd){
    MSG msg;
    bzero(&msg,sizeof(msg));
    recv(client_fd,&msg,sizeof(msg),MSG_WAITALL);
    if(msg.cmd == upload){
        server_upload(client_fd,&msg);
        return 0;
    }
    if(msg.cmd == download){
        server_download(client_fd,&msg);
        return 0;
    }
    return -1;
}

void* threadMain(void *p){
    while(1){

        thread_poll *poll = (thread_poll*)p;
        pthread_mutex_lock(&poll->lock);
        while(poll->sessions.count == 0){
            pthread_cond_wait(&poll->cond,&poll->lock);
        }
        int client_fd = deQueue(&poll->sessions);
        if(client_fd == -1){
            printf("error: empty queue!\n");
            break;
        }
        pthread_mutex_unlock(&poll->lock);
        int ret = work_program(client_fd);
        if(ret == -1){
            printf("error: invalid command");
        }
        close(client_fd);
    }

}

